package ar.org.tesis.comparticion.conocimientos.dao.hbn;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import ar.org.tesis.comparticion.conocimientos.dao.WorldDAO;
import ar.org.tesis.comparticion.conocimientos.informacion.beans.WorldBean;

/**
 * @author mpriet
 *
 */
@SuppressWarnings("serial")
public class WorldDAOHbn extends AbstractDAOHbn implements WorldDAO {

	private static final Logger logger = Logger.getLogger(WorldDAOHbn.class);
	
	public WorldDAOHbn() {
		// TODO Auto-generated constructor stub
	}
	
	public final void guardarWorldBean(final WorldBean worldBean) {
		logger.info("inicio insercion del world");
		this.saveOrUpdate(worldBean);
		logger.info("finalizo la insercion del world");
	}
	
	public final WorldBean buscarWorldBean(final String worldName) {
		logger.info("inicio busqueda del world");
		
		final String queryStr="Select * from WORLD where name=:worldName";
		
		@SuppressWarnings({ "unchecked", "rawtypes" })
		WorldBean worldBean = getHibernateTemplate().execute(
				new HibernateCallback() {
				public Object doInHibernate(Session session) throws HibernateException {
				SQLQuery query =session.createSQLQuery(queryStr);
				query.addEntity(WorldBean.class);
				query.setString("worldName", worldName);
				WorldBean worldBean=(WorldBean)query.uniqueResult();
				return worldBean;
				}});
		 
		 logger.info("finalizo la busqueda del sia");
		 return worldBean;
		 
	}
	
	
	public final Integer buscarIdWorldBean(final String worldName) {
		logger.info("inicio busqueda del world");
		
		final String queryStr="Select id_world from WORLD where name=:worldName";
		
		@SuppressWarnings({ "unchecked", "rawtypes" })
		Integer idWorld = getHibernateTemplate().execute(
				new HibernateCallback() {
				public Object doInHibernate(Session session) throws HibernateException {
				SQLQuery query =session.createSQLQuery(queryStr);
				query.addScalar("id_world", Hibernate.INTEGER);
				query.setString("worldName", worldName);
				List result = query.list();
				if(result==null||result.size()<1)
					return null;
				return result.get(0);
				}});
		 
		 logger.info("finalizo la busqueda del sia");
		 return idWorld;
		 
	}

}
